#!/bin/bash
# Copyright      2017   David Snyder
#                2017   Johns Hopkins University (Author: Daniel Garcia-Romero)
#                2017   Johns Hopkins University (Author: Daniel Povey)
# Apache 2.0.

. ./cmd.sh
. ./path.sh
set -e

stage=7
train_stage=-10

# Options
egs_frame_per_eg=8
use_dense_targets=false
dropout_schedule='0,0@0.20,0.1@0.50,0'
num_epochs=3
samples_per_iter=4000000
init_lr=0.001
final_lr=0.0001
remove_egs=false
srand=123
cleanup=true

data_dir=data/train
nnet_dir=exp/dvector_nnet_1a
ali_dir=exp/spk_ali
egs_dir=

. ./utils/parse_options.sh

if [ $stage -le 7 ]; then
  echo "$0: creating neural net configs using the xconfig parser";
  feat_dim=$(feat-to-dim scp:$data_dir/feats.scp - 2> /dev/null)
  num_targets=`cat $ali_dir/target_num`
  echo feat-dim: $feat_dim
  echo num-targets: $num_targets

  mkdir -p $nnet_dir/configs
  cat <<EOF > $nnet_dir/configs/network.xconfig
  # please note that it is important to have input layer with the name=input

  # The frame-level layers
  input dim=${feat_dim} name=input
  relu-batchnorm-layer name=tdnn1 input=Append(-2,-1,0,1,2) dim=512
  relu-batchnorm-layer name=tdnn2 input=Append(-2,0,2) dim=512
  relu-batchnorm-layer name=tdnn3 input=Append(-3,0,3) dim=512
  relu-batchnorm-layer name=tdnn4 input=Append(-3,0,3) dim=512
  relu-batchnorm-layer name=tdnn5 dim=3000
  relu-batchnorm-layer name=tdnn6 dim=512
  relu-batchnorm-layer name=tdnn7 dim=512
  output-layer name=output include-log-softmax=true dim=${num_targets}
EOF

  steps/nnet3/xconfig_to_configs.py \
      --xconfig-file $nnet_dir/configs/network.xconfig \
      --config-dir $nnet_dir/configs/
  cp $nnet_dir/configs/final.config $nnet_dir/nnet.config
  echo "num_targets=$num_targets" >> $nnet_dir/configs/vars
  echo "output-node name=output input=tdnn6.affine" > $nnet_dir/extract.config
fi

if [ $stage -le 8 ]; then
  steps/nnet3/train_raw_dnn.py --stage=$train_stage \
    --cmd="$cmd" \
    --feat.cmvn-opts="--norm-means=false --norm-vars=false" \
    --egs.opts="--nj 10" \
    --egs.stage=0 \
    --egs.cmd="$train_cmd" \
    --egs.dir="$egs_dir" \
    --egs.frames-per-eg=$egs_frame_per_eg \
    --trainer.srand=$srand \
    --trainer.max-param-change=2.0 \
    --trainer.num-epochs=$num_epochs \
    --trainer.samples-per-iter=$samples_per_iter \
    --trainer.optimization.num-jobs-initial=3 \
    --trainer.optimization.num-jobs-final=8 \
    --trainer.optimization.initial-effective-lrate=$init_lr \
    --trainer.optimization.final-effective-lrate=$final_lr \
    --trainer.optimization.minibatch-size=256,128 \
    --trainer.dropout-schedule="$dropout_schedule" \
    --cleanup.remove-egs=$remove_egs \
    --cleanup.preserve-model-interval=20 \
    --cleanup=$cleanup \
    --use-gpu=wait \
    --use-dense-targets=$use_dense_targets \
    --feat-dir=$data_dir \
    --targets-scp="$ali_dir/ali.scp" \
    --dir=$nnet_dir  || exit 1;
fi

exit 0;
